package org.budo.support.java.net.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.budo.support.lang.util.ThreadUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @author limingwei
 * @date 2016年6月8日 上午9:05:22
 */
@Slf4j
public class JavaNetUrlUtil {
    public static InputStream openStream(URL url, Integer delay, Integer retries) {
        if (null == delay || delay < 1 || null == retries || retries < 1) {
            log.error("#20 openStream, url=" + url + ", delay=" + delay + ", retries=" + retries);
            return openStream(url);
        }

        for (int i = 0; i < retries; i++) {
            try {
                return openStream(url); // 先试
            } catch (Throwable e) {
                log.error("#28 openStream, url=" + url + ", delay=" + delay + ", retries=" + retries + ", i=" + i + ", e=" + e);

                ThreadUtil.sleep(delay); // 失败就稍等
            }
        }

        // 最后一次 失败就抛异常
        return openStream(url);
    }

    public static InputStream openStream(URL url) {
        try {
            return url.openStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static URL newUrl(String spec) {
        try {
            return new URL(spec);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }

    public static URLConnection httpURLConnection(String url) {
        try {
            URL sendUrl = new URL(url);
            URLConnection connection = sendUrl.openConnection();
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(30000);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            ((HttpURLConnection) connection).setInstanceFollowRedirects(false);

            return connection;
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }
}